package chinaums.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import chinaums.common.util.Results;
import chinaums.common.util.ResultsUrl;
import chinaums.common.util.ShortUrlUtil;
import chinaums.dao.LongUrlLinkMapper;
import chinaums.entity.LongUrlLink;
import chinaums.entity.Url;
import chinaums.service.IUrlService;

import com.alibaba.fastjson.JSONObject;

/**
 * <p>Title:UrlRunnable</p>
 * <p>Description:生成短连接的runnable类</p>
 * @version v1.0
 * @author RenLei
 * 2017年7月21日
 */
public class UrlRunnable extends Thread{
	private static Logger log= LoggerFactory.getLogger(UrlRunnable.class);
	private IUrlService urlService;
    private List<LongUrlLink> list;
    private LongUrlLinkMapper mapper;
    private CountDownLatch countDownLatch;
	public UrlRunnable(List<LongUrlLink> list,IUrlService urlService,LongUrlLinkMapper mapper,CountDownLatch countDownLatch) {
		this.list = list;
		this.urlService = urlService;
		this.mapper=mapper;
		this.countDownLatch = countDownLatch;
	}
	@Override
	public void run() {
		try {
			List<Url> uList=new ArrayList<Url>();
			//再次分割数据，并且批量处理20条数据
			List<LongUrlLink> newList=null;
			//获取集合大小
			int otherList=list.size();
			log.info("每个线程获取的集合大小是:"+otherList);
			System.out.println("otherList:"+otherList);
			//定义count数量
			int count=20;
			//定义循环次数
			int timeCount=0;
			//判断集合是否小于count,如果小于就只循环一次，count等于集合大小
			if(otherList<=count){//加一个！=0的判断
				count=otherList;
				timeCount=otherList/count;
			}else{
				if(otherList%count==0){
					timeCount=otherList/count;
				}else{
					timeCount=(otherList/count)+1;
				}
			}
			System.out.println("timeCount:"+timeCount);
			//把数据进行分页
			for(int i=0;i<timeCount;i++){
				if((i+1)==timeCount){
	                int startIndex = (i*count);
	                int endIndex = list.size();
	                newList =list.subList(startIndex,endIndex);
	            }else{
	                int startIndex = i*count;
	                int endIndex = (i+1)*count;
	                newList =list.subList(startIndex,endIndex);
	            }
				System.out.println("newlist大小:"+newList.size());
				log.info("当前线程:"+Thread.currentThread().getName()+"执行的数量是"+newList.size());
				//定义俩个变量来接收值
				String newUrl1 = "";
				StringBuffer sbUrl= new StringBuffer();
				List<Map<String, String>>  list=new ArrayList<Map<String,String>>();
				//遍历newlist集合
				for (int j = 0; j < newList.size(); j++) {
					//避免多台服务器操作同一张表数据重复
					LongUrlLink link=new LongUrlLink();
					link.setId(newList.get(j).getId());
					link.setVersion(newList.get(j).getVersion());
					int result=mapper.updateLongVersion(link);
					if(result==0){
						log.info("该长连接已经被其它服务器执行过了");
						continue;
					}
					if(j!=0){
						//当不是第一个的时候拼接&url_long=字符
						newUrl1=sbUrl.append("&url_long="+newList.get(j).getLongurl()).toString();//将长连接地址加上&url_long=
					}else{
						newUrl1 = sbUrl.append(newList.get(j).getLongurl()).toString();
							}
					
					//将长连接和channelid添加到map中
					Map<String, String> map=new HashMap<String, String>();
					map.put("channelid", newList.get(j).getChannelid().toString());
					map.put("longurl", newList.get(j).getLongurl());
					//将map添加到集合中
					list.add(map);
				}
				if(newUrl1==null||newUrl1.equals("")){
					log.info("newUrl1是空的...."+newUrl1);
					continue;
				}
				log.info("newUrl1内容是-------"+newUrl1);
				//System.out.println("------------短连接-----------"+newurl1);
				String shortJson=ShortUrlUtil.getShortUrl(newUrl1);//获取短链接json
				//System.out.println("------------json-------------"+shortjson);
				//判断shortjson是否为空
				int k=0;
			    //当json为空时再次发送请求，如果超过十次没有返回成功，则跳出循环
				while(StringUtils.isBlank(shortJson)){
					if(k>10){
						log.info("超过10次依然没有请求成功");
						break;
					}
					shortJson=ShortUrlUtil.getShortUrl(newUrl1);
						k=k+1;
				}
				if(shortJson==null || "".equals(shortJson)){
					continue;
				}
				log.info("shortJson为:"+shortJson);
				
				
				//进行json解析，把相应的参数转换
				ResultsUrl ru = JSONObject.parseObject(shortJson, ResultsUrl.class);
				log.info("每次获取的短连接长度："+ru.getUrls().size());
				//获取urls字段的集合
				List<Results> rList = ru.getUrls();
				//遍历集合，把相应的参数插入到url表中
				for(int l =0 ; l<list.size();l++){
					Map<String,String> nmap = list.get(l);
					String id = nmap.get("channelid");
					String slong = nmap.get("longurl");
					for(Results rs :rList){
						//新增url操作
						Url u=new Url();
						if("true".equals(rs.getResult())){
							u.setLongurl(rs.getUrl_long());
							u.setShorturl(rs.getUrl_short());
							if(slong.contains(rs.getUrl_long())){
								u.setChannelid(id);
							}else{
								continue;
							}
							u.setUrlstate(0);
							}else{
							u.setUrlstate(2);
						    }
						//修改长连接表状态
						LongUrlLink link=new LongUrlLink();
						link.setLongurl(rs.getUrl_long());
						link.setLongstate(1);
						mapper.updateLongUrl(link);
						//把数据添加到ulist中在mapper文件中一起插入到url表中
						uList.add(u);
					}
				}
			}
			List<Url> lList=new ArrayList<Url>();
			int listSize=uList.size();
			//定义count数量
			int size=1000;
			//定义循环次数
			int cycleCount=0;
			//判断集合是否小于count,如果小于就只循环一次，count等于集合大小
			if(listSize<=size){//加一个！=0的判断
				size=listSize;
				cycleCount=listSize/size;
			}else{
				if(listSize%size==0){
					cycleCount=listSize/size;
				}else{
					cycleCount=(listSize/size)+1;
				}
			}
			for(int m=0;m<cycleCount;m++){
				if((m+1)==cycleCount){
	                int startIndex = (m*size);
	                int endIndex = uList.size();
	                lList =uList.subList(startIndex,endIndex);
	            }else{
	                int startIndex = m*size;
	                int endIndex = (m+1)*size;
	                lList =uList.subList(startIndex,endIndex);
	            }
				//储存到URL中
				log.info("开始插入..........................");
				urlService.addUrl(lList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//countDownLatch计数
			//关闭辅助类线程
			countDownLatch.countDown();
		}
			}

}
